﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class inventory_movable_item : MonoBehaviour
{
    private Image prop_sprite;// 贴图
    public Text numText;
    public int Count;
    public int id;
    private Objectinfo this_prop;
    public static string SpritePath = "Sprites/prop";
    private bool isOver = false;

    private void Awake()
    {
        numText = transform.Find("Count").GetComponent<Text>();
        numText.gameObject.SetActive(false);
        prop_sprite = gameObject.GetComponent<Image>();
    }
    // Start is called before the first frame update
    void Start()
    {
        initTriggerEvent();
    }

    // Update is called once per frame
    void Update()
    {
        if(isOver)
        {
            Prop_description_Frame._instance.Describe_Prop(this_prop);
            if(Input.GetMouseButton(1))// 加上一个穿戴的功能
            {
                // 如果是背包里面的东西就直接使用
                if(this.transform.parent.tag == Tags.inventory_grid)
                    activate();
                // 如果是装备区的东西就回到包中,把自己删除
                else if(this.transform.parent.tag == Tags.equip_grid)
                {
                    bool result = Inventory._instance.Add_Concrete_Item(this_prop);
                    if (result == false) Debug.Log("背包内已经满了"); 
                    else
                    {
                        inventory_static_grid Grid = this.transform.parent.GetComponent<inventory_static_grid>();
                        Grid.Clear_Grid();
                        Destroy(this.gameObject);
                    }
                }
                else if(this.transform.parent.tag == Tags.container_grid)
                {
                    bool result = Inventory._instance.Add_Concrete_Item(this_prop);
                    if(!result) Debug.Log("背包内已经满了");
                    else
                    {
                        inventory_static_grid Grid = this.transform.parent.GetComponent<inventory_static_grid>();
                        Grid.Clear_Grid();
                        Destroy(this.gameObject);
                    }
                }
            }
        }
    }

    public void Set_Sprite_icon(int id, string atlas_path, string sprite_name)
    {
        this.id = id;
        prop_sprite.overrideSprite = SpriteManager.getInstance().LoadAtlasSprite(atlas_path, sprite_name);
    }

    public void SetId(int id, int num = 1)
    {
        Objectinfo info = ObjectsInfo._instance.getObjectinfobyid(id);
        Set_Prop(info, num);
        Debug.Log("After SetId id:" + id);
    }

    public void Set_Prop(Objectinfo obj, int num = 1)
    {
        this_prop = obj;// 获得这个道具的信息
        Count = num;

        this.id = obj.id;
        Set_Sprite_icon(this_prop.id, this_prop.atlas_path, this_prop.icon_name);
        if (num == 1)
        {
            numText.gameObject.SetActive(false);
        }
        else
        {
            numText.gameObject.SetActive(true);
            numText.text = Count.ToString();
        }
    }

    public void Get_Some(int num = 1)
    {
        Debug.Log("获得了" + num);
        Count += num;
        if(Count > 1)
        {
            numText.gameObject.SetActive(true);
            numText.text = Count.ToString();
        }
        else if(Count == 1)
        {
            numText.gameObject.SetActive(false);
        }
        else if(Count <= 0)// 如果都已经小于零了就直接消除
        {
            transform.parent.GetComponent<inventory_static_grid>().Clear_Grid();
            DestroyImmediate(gameObject);
        }
    }

    public int Get_Count()
    {
        return Count;
    }

    public int Get_Weight()
    {
        return this_prop.weight * Count;
    }
    // 获得这个道具的回复量
    public int Get_HP_Relieve()
    {
        if (this_prop.str_type != Objecttype.drug)
        {
            return 0;
        }
        else return this_prop.hp;
    }

    public void activate()
    {
        Debug.Log("Activate");
        switch (this_prop.str_type)
        {
            case Objecttype.drug:
                PlayerController._instance.Hunger_Change(this_prop.food);
                PlayerController._instance.Thirst_Change(this_prop.water);
                PlayerController._instance.HP_Change(this_prop.hp);
                PlayerController._instance.Get_Radiation(this_prop.radiation);
                if(this_prop.cause_buffID != 0)
                {
                    PlayerController._instance.Get_Buff(this_prop.cause_buffID);
                }
                if(this_prop.defuse_buffID != 0)
                {
                    PlayerController._instance.Eliminate_Buff(this_prop.defuse_buffID);
                }

                this.Count -= 1;
                if (this.Count == 0)
                {
                    transform.parent.GetComponent<inventory_static_grid>().Clear_Grid();
                    Destroy(gameObject);
                }
                break;
            case Objecttype.equipment:
                {
                    inventory_static_grid Target_Grid;
                    inventory_static_grid Origin_Grid = transform.parent.GetComponent<inventory_static_grid>();
                    
                    // 先获得对应的装备区的格子和自己对应的格子
                    switch(this_prop.equip_Type)
                    {
                        case Equip_type.Armor:
                            Target_Grid = Inventory._instance.armor;
                            break;
                        case Equip_type.Hands:
                            Target_Grid = Inventory._instance.wrist;
                            break;
                        case Equip_type.Headgear:
                            Target_Grid = Inventory._instance.helmet;
                            break;
                        case Equip_type.Legs:
                            Target_Grid = Inventory._instance.legs;
                            break;
                        case Equip_type.Shoes:
                            Target_Grid = Inventory._instance.shoe;
                            break;
                        case Equip_type.Sub_Weapon:
                            Target_Grid = Inventory._instance.sub_weapon;
                            break;
                        case Equip_type.Weapon:
                            Target_Grid = Inventory._instance.main_weapon;
                            break;
                        default:
                            return;
                    }
                    // 如果原本的装备格子是空的
                    if (Target_Grid.id == 0)
                    {
                        gameObject.tag = Tags.equip_item;
                        transform.SetParent(Target_Grid.transform);
                        Target_Grid.SetId(id);

                        Origin_Grid.Clear_Grid();
                    }
                    else// 如果已经有装备了就交换对应的内容
                    {
                        inventory_movable_item exist_equip = Target_Grid.Get_item_inside();

                        // 改变父母层级的关系
                        exist_equip.transform.SetParent(Origin_Grid.transform);
                        transform.SetParent(Target_Grid.transform);
                        // 改变tag
                        exist_equip.gameObject.tag = Tags.inventory_item;
                        gameObject.tag = Tags.equip_item;
                        // 改变格子上面的id
                        Target_Grid.ChangeId(this.id);
                        Origin_Grid.ChangeId(exist_equip.id);

                        exist_equip.Reset_Location();
                        /*int temp_id = Target_Grid.id;

                        Target_Grid.SetId(this_prop.id, 1);
                        Origin_Grid.SetId(temp_id, 1);*/
                    }

                    Inventory._instance.Refresh_Equip_Attibute();// 重置装备区的数据
                }
                break;
            default:
                break;
        }

        Inventory._instance.Get_Load();
    }

    public void Reset_Location()
    {
        this.transform.localPosition = Vector3.zero;
    }

    public Objectinfo GetObjectinfo()
    {
        return this_prop;
    }

    public void initTriggerEvent()
    {
        EventTrigger trigger = gameObject.AddComponent<EventTrigger>();

        EventTrigger.Entry dragentry = new EventTrigger.Entry();// 创建一个拖动的事件
        dragentry.eventID = EventTriggerType.Drag;
        dragentry.callback = new EventTrigger.TriggerEvent();
        dragentry.callback.AddListener(Being_Drag_Listener);

        EventTrigger.Entry enddragentry = new EventTrigger.Entry();
        enddragentry.eventID = EventTriggerType.EndDrag;
        enddragentry.callback = new EventTrigger.TriggerEvent();
        enddragentry.callback.AddListener(End_Drag_Listener);

        EventTrigger.Entry startdragentry = new EventTrigger.Entry();
        startdragentry.eventID = EventTriggerType.BeginDrag;
        startdragentry.callback = new EventTrigger.TriggerEvent();
        startdragentry.callback.AddListener(Begin_Drag_Listener);

        EventTrigger.Entry mouseoverEntry = new EventTrigger.Entry();
        mouseoverEntry.eventID = EventTriggerType.PointerEnter;
        mouseoverEntry.callback = new EventTrigger.TriggerEvent();
        mouseoverEntry.callback.AddListener(OnPointerEnter);

        EventTrigger.Entry mouseexitEntry = new EventTrigger.Entry();
        mouseexitEntry.eventID = EventTriggerType.PointerExit;
        mouseexitEntry.callback = new EventTrigger.TriggerEvent();
        mouseexitEntry.callback.AddListener(OnPointerExit);

        trigger.triggers.Add(dragentry);
        trigger.triggers.Add(enddragentry);
        trigger.triggers.Add(startdragentry);
        trigger.triggers.Add(mouseoverEntry);
        trigger.triggers.Add(mouseexitEntry);
    }

    public void Begin_Drag_Listener(BaseEventData eventData)
    {
        Debug.Log("开始拖拽事件");
    }

    public void Being_Drag_Listener(BaseEventData eventData)
    {
        Vector2 touchpos = ((PointerEventData)eventData).position;
        /* Vector2 uguiPos;

        // 将屏幕坐标变为本地坐标
        bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(
            Parent, touchpos, ((PointerEventData)eventData).enterEventCamera, out uguiPos);
        // 如果拖动位置在区域内
        if (isRect && RectTransformUtility.RectangleContainsScreenPoint(Parent, touchpos, ((PointerEventData)eventData).enterEventCamera))
            // 更新被拖动的位置
            */

        prop_sprite.rectTransform.position = touchpos;
        //prop_pic.rectTransform.localPosition = uguiPos;
        prop_sprite.raycastTarget = false;// 拖动时防止阻挡射线探测
    }

    public void End_Drag_Listener(BaseEventData eventData)
    {
        // 获取指向的目标
        var target = ((PointerEventData)eventData).pointerEnter;
        if (target != null)
        {
            if (target.CompareTag(Tags.inventory_grid) || target.CompareTag(Tags.container_grid))// 普通的格子
            {
                if (target == this.transform.parent.gameObject)
                {
                    // 如果回到了自己的格子那边就什么都不做
                }
                else
                {
                    inventory_static_grid Origin_grid = this.transform.parent.GetComponent<inventory_static_grid>();
                    inventory_static_grid Target_grid = target.GetComponent<inventory_static_grid>();

                    this.transform.SetParent(target.transform);
                    gameObject.tag = Tags.inventory_item;// 要考虑到可能是装备的移动
                    Target_grid.ChangeId(this_prop.id);

                    Origin_grid.Clear_Grid();// 清除原本格子的数据
                }
                Inventory._instance.Get_Load();
            }
            else if (target.CompareTag(Tags.inventory_item))// 有物品的格子
            {
                inventory_static_grid Origin_grid = this.transform.parent.GetComponent<inventory_static_grid>();
                inventory_static_grid Target_grid = target.transform.parent.GetComponent<inventory_static_grid>();
                inventory_movable_item Target_item = target.GetComponent<inventory_movable_item>();

                if (gameObject.tag == Tags.equip_item && Target_item.GetObjectinfo().equip_Type != this_prop.equip_Type)
                {
                    // 如果是装备移到不对应的物品上面
                    // 如果不是同一种装备类型，就直接退回
                }
                else
                {
                    if(this_prop.id == Target_item.id && this_prop.str_type != Objecttype.equipment)// 如果是相同的id
                    {
                        Target_item.Get_Some(Count);

                        Debug.Log("物体合并");
                        Origin_grid.Clear_Grid();
                        prop_sprite.raycastTarget = true;
                        Destroy(gameObject);
                        return;
                    }
                    else
                    {
                        int temp_count = Get_Count();
                        int temp_id = this_prop.id;

                        Target_item.transform.SetParent(Origin_grid.transform);
                        transform.SetParent(Target_grid.transform);
                        Origin_grid.ChangeId(Target_item.id);
                        Target_grid.ChangeId(temp_id);

                        Target_item.Reset_Location();
                    }
                    Inventory._instance.Get_Load();
                }
            }
            else if (target.CompareTag(Tags.equip_item))// 如果移动到了装备的道具上面
            {
                if(this_prop.str_type != Objecttype.equipment)
                {
                    // 如果这个道具本身并不是装备那就直接略掉
                }
                else// 如果这个道具是装备就考虑是否是对应的种类让后换掉
                {
                    Objectinfo targetinfo = target.GetComponent<inventory_movable_item>().GetObjectinfo();
                    if(targetinfo.equip_Type == this_prop.equip_Type)// 如果相同就顶掉
                    {
                        inventory_static_grid Origin_grid = this.transform.parent.GetComponent<inventory_static_grid>();
                        inventory_static_grid Target_grid = target.transform.parent.GetComponent<inventory_static_grid>();
                        inventory_movable_item Target_item = target.GetComponent<inventory_movable_item>();

                        // 改变父母层级的关系
                        Target_item.transform.SetParent(Origin_grid.transform);
                        transform.SetParent(Target_grid.transform);
                        // 改变tag
                        Target_item.gameObject.tag = Tags.inventory_item;
                        gameObject.tag = Tags.equip_item;
                        // 改变格子上面的id
                        Target_grid.ChangeId(this.id);
                        Origin_grid.ChangeId(Target_item.id);

                        Target_item.Reset_Location();

                        /*int temp_count = Get_Count();
                        int temp_id = this_prop.id;

                        Origin_grid.SetId(Target_item.id, Target_item.Get_Count());
                        Target_grid.SetId(temp_id, temp_count);*/
                    }
                    else
                    {
                        // 如果装备种类不相同，还是无事发生
                    }
                }
            }
            else if(target.CompareTag(Tags.equip_grid))// 如果移动到了装备的格子
            {
                if((target.name == "helmet" && this_prop.equip_Type == Equip_type.Headgear)
                    ||(target.name == "wrist" && this_prop.equip_Type == Equip_type.Hands)
                    ||(target.name == "armor" && this_prop.equip_Type == Equip_type.Armor)
                    ||(target.name == "leg" && this_prop.equip_Type == Equip_type.Legs)
                    ||(target.name == "shoe" && this_prop.equip_Type == Equip_type.Shoes)
                    ||(target.name == "main_weapon" && this_prop.equip_Type == Equip_type.Weapon)
                    ||(target.name == "sub_weapon" && this_prop.equip_Type == Equip_type.Sub_Weapon))
                {
                    inventory_static_grid Origin_grid = this.transform.parent.GetComponent<inventory_static_grid>();
                    inventory_static_grid Target_grid = target.GetComponent<inventory_static_grid>();

                    this.transform.SetParent(target.transform);
                    this.transform.tag = Tags.equip_item;

                    Target_grid.ChangeId(id);// 更换格子的id
                    Origin_grid.Clear_Grid();// 清除原本格子的数据
                }
                else
                {
                    // 如果不是对应的装备就直接会回到原本的位置
                }
            }
        }
        else
        {
            //prop_sprite.rectTransform.position = originRect;
        }

        Reset_Location();// 重置相对位置
        if (target != null) Debug.Log(target.name);
        prop_sprite.raycastTarget = true;
        Inventory._instance.Get_Load();
        Craft_List._instance.Refresh_Craft_Table();
        Inventory._instance.Refresh_Equip_Attibute();// 重置装备区的数据
    }

    public void OnPointerEnter(BaseEventData eventData)
    {
        isOver = true;
    }

    public void OnPointerExit(BaseEventData eventData)
    {
        isOver = false;
    }
}
